package com.squirrel.facade;

import com.alibaba.fastjson.util.TypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedCaseInsensitiveMap;

import java.io.Serializable;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author wangyan
 */
public class DataMedium extends LinkedCaseInsensitiveMap implements SqlOperate, Serializable {

    private static final Logger log = LoggerFactory.getLogger(DataMedium.class);

    private String tabName;

    public DataMedium() {
    }

    public DataMedium(Map<String, Object> map) {
        this.putAll(map);
    }

    public DataMedium(String tabName, Map<String, Object> map) {
        this.tabName = tabName;
        this.putAll(map);
    }

    public String getTabName() {
        return tabName;
    }

    /**
     * 如果是从一张表中查出来的数据，重新插入到新表，需要调用此方法将操作的新表名传进来
     * 最好new DataMedium()对象，传入新表数据，除非旧表字段和新表一样，并且旧表字段大于新表时，可以使用当前DataMedium()对象
     *
     * @param tabName
     */
    public void setTabName(String tabName) {
        this.tabName = tabName;
    }


    /**
     * 设置字段值
     *
     * @param field
     * @return
     */
    public void setField(String field, Object object) {
        this.put(field, object);
    }


    /**
     * 用于更新操作的字段
     *
     * @param key
     * @param value
     * @return
     */
    public Map<String, Object> setUpdateFields(String key, Object value) {
        this.put(key, value);
        return this;
    }


    /**
     * 获取string类型的数据
     *
     * @param field
     * @return
     */
    public String getStringField(String field) {
        return (String) this.get(field);
    }

    /**
     * 获取int类型的数据
     *
     * @param field
     * @return
     */
    public Integer getNumberField(String field) {
        //java.math.BigDecimal cast to java.lang.Integer
        Integer i = null;
        try {
            i = Integer.parseInt(this.get(field).toString());
        } catch (NullPointerException e) {
            log.debug("字段:{}获取的值为null", field);
        } catch (ClassCastException e) {
            log.error("字段:{}类型转换错误{}", field, e);
        }
        return i;
    }

    /**
     * 获取Long类型的数据
     * 比如uuid
     *
     * @param field
     * @return
     */
    public Long getLongField(String field) {
        //java.math.BigDecimal cast to java.lang.Long
        return Long.parseLong(this.get(field).toString());
    }


    /**
     * 将获取的数据库Timestamp转为LocalDateTime
     *
     * @param field
     * @return
     */
    public LocalDateTime getTIMESTAMP(String field) {
        Timestamp timestamp = (Timestamp) this.get(field);
        return timestamp.toLocalDateTime();
    }

    public long getCount() {
        Object count = this.get("count");
        return TypeUtils.castToLong(count);
    }
}
